package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.Commodity;
import cn.wolfcode.luowowo.article.domain.UserCommodity;
import cn.wolfcode.luowowo.article.domain.UserGold;
import cn.wolfcode.luowowo.article.mapper.CommodityMapper;
import cn.wolfcode.luowowo.article.mapper.UserCommodityMapper;
import cn.wolfcode.luowowo.article.mapper.UserGoldMapper;
import cn.wolfcode.luowowo.article.query.CommodityQuery;
import cn.wolfcode.luowowo.article.service.IShopService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;


@Service
public class ShopServiceImpl implements IShopService {



    @Autowired
    private CommodityMapper commodityMapper;

    @Autowired
    private UserCommodityMapper userCommodityMapper;

    @Autowired
    private UserGoldMapper userGoldMapper;

    @Override
    public PageInfo query(UserInfo userInfo,Long queryType, CommodityQuery query) {


        PageInfo<Object> pageInfo = new PageInfo<>();

        Long uid = userInfo.getId();

        PageHelper.startPage(query.getCurrentPage(),query.getPageSize());

        if (queryType == 0){

            //所有的商品
            List<Commodity> commodities = commodityMapper.selectAll();

            return new PageInfo(commodities);

        }
        List<UserCommodity> userCds = userCommodityMapper.selectByUserId(uid);

        //所有已经拥有的商品

        return new PageInfo(userCds);
    }


    @Override
    public int buy(Long uid, Long id) {

        //查出是哪个商品
        Commodity commodity = commodityMapper.selectByPrimaryKey(id);

        int price = commodity.getPrice().intValue();
        //不够钱
        UserGold userGold = userGoldMapper.selectByPrimaryKey(uid);
        if (userGold.getCoin() < price){
            return UserGold.NO_MONEY;
        }

        //没货了
        if (commodity.getNumber() == 0){
            return Commodity.NO_NUMBER;
        }

        //添加进去用户 和 商品 关系表
        UserCommodity userCommodity = new UserCommodity(uid, id, commodity.getName(), commodity.getInfo(), commodity.getCoverUrl(), new Date(),new Commodity());
        userCommodityMapper.insert(userCommodity);

        //减少商品数量
        commodityMapper.updateNumber(commodity.getNumber() - 1,id);

        //用户金币减少
        userGold.setCoin(userGold.getCoin() - commodity.getPrice().intValue());
        userGoldMapper.updateByPrimaryKey(userGold);

        return 0;

    }
}
